package cn.zhf.shop.service.impl;

import cn.hutool.json.JSONUtil;
import cn.zhf.shop.entity.ConsoleUser;
import cn.zhf.shop.entity.Message;
import cn.zhf.shop.entity.Refund;
import cn.zhf.shop.entity.campus.CamOverview;
import cn.zhf.shop.entity.organization.OrgOverview;
import cn.zhf.shop.entity.search.ConsoleUserSearch;
import cn.zhf.shop.mapper.CampusMapper;
import cn.zhf.shop.mapper.ConsoleUserMapper;
import cn.zhf.shop.mapper.OrganizationMapper;
import cn.zhf.shop.service.CampusService;
import cn.zhf.shop.service.ConsoleUserService;
import cn.zhf.shop.service.OrgCampusService;
import cn.zhf.shop.service.OrganizationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@Component
public class ConsoleUserServiceImpl implements ConsoleUserService {
    @Resource
    private ConsoleUserMapper consoleUserMapper;
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Resource
    private OrganizationMapper organizationMapper;

    @Resource
    private CampusMapper campusMapper;


    @Override
    public Message<?> appendUser(ConsoleUser consoleUser) {
        logger.info("添加用户：{}", JSONUtil.toJsonStr(consoleUser));
        return consoleUserMapper.insert(consoleUser) > 0 ? Message.success(null) : Message.fail(null);
    }

    @Override
    public Message<HashMap> getByUsername(String username, String password) {
        ConsoleUser user = new ConsoleUser();
        ConsoleUser user1 = consoleUserMapper.doLogin(username, password);

        if (user1 == null) {
            ConsoleUser user2 = consoleUserMapper.selectByUserPhoneAndPassword(username, password);
            user = user2;
        } else if (user1 != null) {
            user = user1;
        }
        HashMap refund = new HashMap();
        if (user != null) {
            logger.info("登录查询：username：{},password:{},2130," + user.getUserGroup(), username, password);

            refund.put("userId", user.getUserId());
            switch (user.getUserGroup()) {
                case 1:
                    refund.put("userRole", "1");
                    refund.put("data", null);
                    break;
                case 2:
                    refund.put("userRole", "2");
                    OrgOverview o = organizationMapper.selectByHead2(user.getUserId());
                    if (o != null) {
                        refund.put("OCId", o.getOrgId());
                        refund.put("OCName", o.getOrgName());
                    }
                    if (o == null) {
                        refund.put("OCId", "null");
                        refund.put("OCName", "null");
                    }

                    break;
                case 3:
                    refund.put("userRole", "3");

                    OrgOverview o1 = organizationMapper.selectByHead3(user.getUserId());
                    refund.put("OCId", o1.getOrgId());
                    refund.put("OCName", o1.getOrgName());
                    break;
                case 4:
                    refund.put("userRole", "4");
                    CamOverview c = campusMapper.searchByHead(user.getUserId());
                    refund.put("OCId", c.getCampusId());
                    refund.put("OCName", c.getCampusName());
                    break;
                case 5:
                    refund.put("userRole", "5");
                    refund.put("data", null);
                    break;
                case 6:
                    refund.put("userRole", "6");
                    refund.put("data", null);
                    break;
                default:
                    return Message.fail("登陆失败或用户无权限");
            }
        }


        return user == null ? Message.fail("登陆失败") : Message.success("123").add(refund);
    }


    @Override
    public Message<?> removeById(Integer userID) {
        return Message.success(null).add(consoleUserMapper.deleteByPrimaryKey(userID));
    }

    @Override
    public Message<ConsoleUser> selectByUserId(@NotBlank(message = "UserId不得为空") int userId) {
        logger.info("登录查询：username：{}", userId);
        ConsoleUser refund = consoleUserMapper.selectByPrimaryKey(userId);
        return refund == null ? Message.fail("未查到此用户") : Message.success(null).add(refund);
    }

    @Override
    public Message<List<ConsoleUser>> selectAll() {
        logger.info("获得用户列表");
        List<ConsoleUser> refund = consoleUserMapper.selectAll();
        return refund == null ? Message.fail("空") : Message.success(null).add(refund);
    }

    @Override
    public Message<?> updatePwd(int id, String pwd) {
        return consoleUserMapper.updatePasswordByUserId(pwd, id) > 0 ? Message.success(null) : Message.fail(null);
    }


    @Override
    public int deleteByPrimaryKey(Integer userId) {
        return consoleUserMapper.deleteByPrimaryKey(userId);
    }

    @Override
    public int insert(ConsoleUser record) {
        return consoleUserMapper.insert(record);
    }

    @Override
    public int insertSelective(ConsoleUser record) {
        return consoleUserMapper.insertSelective(record);
    }

    @Override
    public ConsoleUser selectByPrimaryKey(Integer userId) {
        return consoleUserMapper.selectByPrimaryKey(userId);
    }

    @Override
    public Message updateByPrimaryKeySelective(ConsoleUser record) {
        return consoleUserMapper.updateByPrimaryKeySelective(record) > 0 ? Message.success(null) : Message.fail(null);
    }

    @Override
    public int updateByPrimaryKey(ConsoleUser record) {
        return consoleUserMapper.updateByPrimaryKey(record);
    }

    /**
     * 模糊搜索
     *
     * @param str
     * @return
     */
    @Override
    public Message<List<ConsoleUser>> selectByUserIdAndOrgIdAndUserGroupAndUsername(String str) {
        if (str.equals("分支机构管理员")) {
            return Message.success(null).add(consoleUserMapper.selectByUserGroup1(4));
        } else if (str.equals("机构管理员")) {
            return Message.success(null).add(consoleUserMapper.selectByUserGroup1(3));
        } else if (str.equals("推荐人员")) {
            return Message.success(null).add(consoleUserMapper.selectByUserGroup1(2));
        } else if (str.equals("系统管理员")) {
            return Message.success(null).add(consoleUserMapper.selectByUserGroup1(1));
        }
        return Message.success(null).add(consoleUserMapper.selectByUserIdAndOrgIdAndUserGroupAndUsername(str));
    }

    @Override
    public Message<List<ConsoleUser>> selectByUserIdAndOrgIdAndUserGroupAndUsername2(Integer userId, Integer orgId, Integer userGroup, String username) {
        return Message.success(null).add(consoleUserMapper.selectByUserIdAndOrgIdAndUserGroupAndUsername2(userId, orgId, userGroup, username));
    }

    @Override
    public Message<List<ConsoleUser>> selectByUserGroup(int userGroup) {
        return Message.success(null).add(consoleUserMapper.selectByUserGroup(userGroup));
    }

    @Override
    public Message<List<ConsoleUser>> selectByUserGroup1(int userGroup) {
        return Message.success(null).add(consoleUserMapper.selectByUserGroup(userGroup));
    }

    @Override
    public Message selectByUserId2() {
        List<ConsoleUser> consoleUserList = consoleUserMapper.selectByUserGroup(2);
        List<ConsoleUser> leaders =  consoleUserMapper.selectByUserGroupAndAgentLeader(2,1);
        List<Map> mapList = new LinkedList<>();
        for (ConsoleUser consoleUser:consoleUserList){
            HashMap hashMap = new HashMap();
            hashMap.put("consoleUserId",consoleUser.getUserId());
            hashMap.put("consoleRealName",consoleUser.getRealname());
            hashMap.put("consoleUserGroup",consoleUser.getUserGroup());
            hashMap.put("consoleOperationStatus",consoleUser.getOperationStatus());
            int flag=0;
            for (ConsoleUser leader:leaders){
                String SubordinateId = leader.getSubordinateId();
                if(SubordinateId!=null){
                    String[] userids = SubordinateId.split(";");
                    for (String useridd:userids){
                        if (consoleUser.getUserId()==Integer.parseInt(useridd)){
                            flag=1;
                            hashMap.put("LeaderRealName",leader.getRealname());
                            break;
                        }
                    }
                }
                if (flag==1)
                    break;
            }
            if (flag==0){
                hashMap.put("LeaderRealName",null);
            }
            mapList.add(hashMap);
        }
        return Message.success(null).add(mapList);

    }
    @Override
    public Message judgmentUserName(String userName) {
        if (consoleUserMapper.selectByUsername(userName) != null) {
            return Message.success("该昵称已存在！");
        }
        return Message.success("该昵称可用！");
    }

    @Override
    public Message mohuConditionSearch(ConsoleUserSearch consoleUserSearch) {
        return Message.success(null).add(consoleUserMapper.selectByOrgIdAndUserGroupAndUsername(consoleUserSearch));
    }

    @Override
    public Message getAllHeadreallyNameandNameByuserGroup(int userGroup) {
        List<ConsoleUser> consoleUserList = consoleUserMapper.selectByUserGroup(userGroup);
        List<Map> mapList = new LinkedList<>();

        for (ConsoleUser consoleUser : consoleUserList) {
            Map data = new HashMap<String, String>();
            data.put("id", consoleUser.getUserId());
            data.put("name", consoleUser.getUsername() + " <" + consoleUser.getRealname() + ">");
            mapList.add(data);
        }

        return Message.success(null).add(mapList);
    }

    @Override
    public Message getAllHeadreallyNameandNameByUserId(int userId) {

        ConsoleUser consoleUser = consoleUserMapper.selectByPrimaryKey(userId);
        Map data = new HashMap<String, String>();
        data.put("id", consoleUser.getUserId());
        data.put("name", consoleUser.getUsername() + " <" + consoleUser.getRealname() + ">");
        return Message.success(null).add(data);
    }

    @Override
    public Message addSubordinate(int userId, ConsoleUser consoleUser) {
        if (consoleUserMapper.insertSelective(consoleUser) > 0) {
            logger.info("添加下属的直辖代理人成功！");
            ConsoleUser record = consoleUserMapper.selectByUsername(consoleUser.getUsername());
            ConsoleUser consoleUser1 = consoleUserMapper.selectByPrimaryKey(userId);
            return consoleUserMapper.updateSubordinateIdByUserId(consoleUser1.getSubordinateId() + record.getUserId().toString() + ";", userId) > 0 ? Message.success(null) : Message.fail(null);
        }
        return Message.fail("添加下属的直辖代理人失败");

    }

    @Override
    public Message judgmentupdateuserName(int userid, String userName) {
        List<ConsoleUser> consoleUserList = consoleUserMapper.selectAll();
        for (ConsoleUser consoleUser : consoleUserList) {
            if (consoleUser.getUsername().equals(userName)) {
                if (consoleUser.getUserId() == userid) {
                    return Message.success("该昵称可用！");
                } else {
                    return Message.success("该昵称已存在！");
                }
            }
        }
        return Message.success("该昵称可用！");
    }

    @Override
    public Message getSubordinateById(int userId) {
        ConsoleUser c = consoleUserMapper.selectByPrimaryKey(userId);
        List<ConsoleUser> consoleUserList = new LinkedList<>();
        if (c.getSubordinateId() != null) {
            String[] userids = c.getSubordinateId().split(";");
            if (userids.length > 0) {
                int[] arr = new int[userids.length];
                int q=0;
                for (String userid : userids) {
                    arr[q]=Integer.parseInt(userid);
                    q++;
                }
                for (int i = 0; i < arr.length; i++) {
                    for (int j = 0; j < arr.length - 1 - i; j++) {
                        if (arr[j] < arr[j + 1]) {
                            int temp = arr[j];
                            arr[j] = arr[j + 1];
                            arr[j + 1] = temp;
                        }
                    }
                }
                for (Integer userid : arr) {
                    ConsoleUser consoleUser = consoleUserMapper.selectByPrimaryKey(userid);
                    consoleUserList.add(consoleUser);
                }
            }
        }

        return Message.success(null).add(consoleUserList);


    }

    @Override
    public Message selectAllexceptUsereGroup2() {
        List<ConsoleUser> consoleUserList = consoleUserMapper.selectAll();
        List<ConsoleUser> consoleUsers = new LinkedList<>();
        for (ConsoleUser consoleUser : consoleUserList) {
            if (consoleUser.getUserGroup() != 2) {
                consoleUsers.add(consoleUser);
            }
        }
        return Message.success(null).add(consoleUsers);
    }

    @Override
    public Message userGroup2MohuSearch(String str) {
        return Message.success(null).add(consoleUserMapper.selectByRealnameMohuSearch(str));
    }

    @Override
    public Message getSubordinateByIdMohuSearch(int userId, String str) {
        ConsoleUser c = consoleUserMapper.selectByPrimaryKey(userId);
        List<ConsoleUser> consoleUserReult = consoleUserMapper.selectByRealnameMohuSearch(str);
        List<ConsoleUser> consoleUserList = new LinkedList<>();
        if (c.getSubordinateId() != null) {


            String[] userids = c.getSubordinateId().split(";");
            if (userids.length > 0) {
                for (ConsoleUser consoleUser : consoleUserReult) {
                    for (String userid : userids) {
                        if (consoleUser.getUserId() == Integer.parseInt(userid))
                            consoleUserList.add(consoleUser);
                    }
                }
            }
        }
        return Message.success(null).add(consoleUserList);
    }



}







